<?php


namespace App\Http\Controllers\Backend;

use App\Events\FileCreatedEvent;
use App\Http\Requests\ApiV2\UploadRequest;
use App\Services\Company\Interfaces\CompanyServiceInterface;
use App\Services\Company\Models\CompanyCategory;
use App\Services\Company\Services\CompanyService;
use App\Services\Business\Models\File;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Services\Business\Interfaces\AttachServiceInterface;
use App\Services\Business\Services\AttachService;
use App\Services\Business\Interfaces\CompanyCategoryServiceInterface;
use App\Services\Business\Services\CompanyCategoryService;


class FileController extends BaseController
{

    /**
     * @var CompanyService
     */
    protected $CompanyService;
    /**
     * @var CompanyCategoryService
     */
    protected $CompanyCategoryService;

    public function __construct(
        CompanyCategoryServiceInterface $CompanyCategoryService,
        CompanyServiceInterface  $CompanyService

    )
    {
        $this->CompanyCategoryService = $CompanyCategoryService;
        $this->CompanyService= $CompanyService;

    }


    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request)
    {

        $companyId = $this->check()?$this->loginCompanyId():$request->input('company_id');
        $userIds = $request->input('user_ids');
        $cid = $request->input('cid');
        $userId = $request->input('user_id');
        $keywords = $request->input('keywords', '');
        $excludeIds  = $request->input('exclude_ids',[]);
        // 排序
        $sort = $request->input('sort', 'created_at');
        $order = $request->input('order', 'desc');

        $files = File::query()
            ->with(['user'])
            ->when($keywords, function ($query) use ($keywords) {
                return $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->when($cid, function ($query) use ($cid) {
                $ids = [$cid];
                $childrenIds = CompanyCategory::query()
                    ->where('parent_id', $cid)
                    ->select(['id'])
                    ->get()
                    ->pluck('id')
                    ->toArray();
                $ids = array_merge($ids, $childrenIds);
                $query->whereIn('category_id', $ids);
            })
            ->when($excludeIds, function ($query) use ($excludeIds) {
                $query->whereNotIn('id',$excludeIds);
            })
            ->when($userIds, function ($query) use ($userIds) {
                return $query->whereIn('id', $userIds);
            })
            ->when($userId, function ($query) use ($userId) {
                $query->where('user_id', $userId);
            })
            ->where("company_id", $companyId)
            ->orderBy($sort, $order)
            ->paginate($request->input('size', 10));
        return $this->successData(compact('files'));
    }


    /**
     * @param UploadRequest $request
     * @param File $file
     * @return JsonResponse
     */
    public function upload(UploadRequest $request, File $file)
    {


        $data = $request->filldata();
        $file->fill($data)->save();
        return $this->successData(compact('file'));


    }

    /**
     * @param UploadRequest $request
     * @param $id
     * @return JsonResponse
     */
    public function detail(UploadRequest $request, $id)
    {


        $file = File::query()->with(['user'])->where('id', $id)->firstOrFail()->toArray();
        return $this->successData(compact('file'));


    }

    //文件已经保存到本地数据，不仅仅以删除oss的文件，还要删除本地数据的文件
    public function delete($id)
    {
        $file = File::query()->where('id', $id)->firstOrFail();

        // 删除附件
        Storage::disk('oss')->delete($file['path']);

        // 删除数据库记录
        $file->delete();

        return $this->success(__('文件删除成功'));

    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function batchDelete(Request $request)
    {

        $ids = $request->input('ids');
            if (!$ids) {
                return   $this->error(__('参数错误'));
            }
        $paths = File::whereIn('id', $ids)->whereIn('id',$ids)->select(['path'])->get()->pluck('path')->toArray();
        // 删除附件
        Storage::disk('oss')->delete($paths);

        // 删除数据库记录
        File::destroy($ids);

        return $this->success(__('文件删除成功'));
    }


    /**
     * @param UploadRequest $request
     * @param $id
     * @return JsonResponse
     */
    public function replace(UploadRequest $request, $id)
    {
        $data = $request->filldata();
        $file = File::query()->where('id', $id)->firstOrFail();
        //删除阿里云附件
        Storage::disk('oss')->delete($file['path']);
        $file->fill($data)->save();
        return $this->success(__('文件替换成功'));

    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function updateTitle(Request $request, $id)
    {
        $title = $request->input('title');
        $file = File::query()->where('id', $id)->firstOrFail();
        $file->update(['title' => $title]);
        return $this->success();
    }

    /**
     * @param Request $request
     * @param string $type
     * @param int $id
     * @return JsonResponse
     */
    public function storeResourceFiles(Request $request, string $type, int $id)
    {
        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($id);
        $ids = (array)$request->input("ids", []);
        if (empty($id) || empty($ids)) {
            return $this->error(__('参数错误'));
        }
        $resource->files()->attach($ids);
        return $this->success(__('添加文件成功'));


    }

    /**
     * @param Request $request
     * @param string $type
     * @param int $id
     * @return JsonResponse
     */
    public function deleteResourceFiles(Request $request, string $type, int $id)
    {
        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($id);
        $ids = (array)$request->input("ids", []);
        if (empty($ids) || empty($ids)) {
            return $this->error(__('参数错误'));
        }
        $resource->files()->detach($ids);
        return $this->success(__('删除文件成功'));
    }


    /**
     * @param $id
     * @return void
     */
    public function download($id)
    {
        $file = File::query()->where('id', $id)->first();

         $this->downFile($file->url,$file->title);


    }



}
